﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.Platform.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("pos-integral")]
    public class PosIntegralController : BaseController<PosIntegral, PosIntergralPagingDto>
    {
        private readonly IPosMemberService posMemberService;
        public PosIntegralController(IPosMemberService posMemberService)
        {
            this.posMemberService = posMemberService;
        }

        protected override async Task<IQueryable<PosIntegral>> FilterQueryPaging(DbContext db, IQueryable<PosIntegral> query, PosIntergralPagingDto dto)
        {
            await Task.CompletedTask;

            if (dto.HasMemberCondition())
            {
                var memberQuery = db.Set<PosMember>().AsNoTracking();
                if (!string.IsNullOrWhiteSpace(dto.memberName))
                {
                    memberQuery = memberQuery.Where(x => x.memberName.Contains(dto.memberName));
                }
                if (!string.IsNullOrWhiteSpace(dto.memberNo))
                {
                    memberQuery = memberQuery.Where(x => x.No.Contains(dto.memberNo));
                }
                if (!string.IsNullOrWhiteSpace(dto.memberTel))
                {
                    memberQuery = memberQuery.Where(x => x.memberTel.Contains(dto.memberTel));
                }

                var memberIds = memberQuery.Select(x => x.Id);

                query = query.Where(x => memberIds.Contains(x.memberID));
            }

            return query;
        }

        public override async Task<ResponseEntity<PagedResultDto<PosIntegral>>> QueryPaging([FromBody] PosIntergralPagingDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res.Data?.Items?.Any() ?? false)
            {
                res.Data.Items = await this.posMemberService.AttachPosMember(res.Data.Items.ToArray());
            }

            return res;
        }
    }
}
